//
//  NIBasePhotoViewController.m
//  AIWAYS
//
//  Created by Marx on 2018/6/14.
//  Copyright © 2018年 wlq. All rights reserved.
//

#import "NIBasePhotoViewController.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "NIDatePickerView.h"
#import "AppContext.h"
#import "NIBasePhotoViewModel.h"
#import "NotificationDefines.h"
#import "NIAvatarObject.h"

@interface NIBasePhotoViewController ()<NIDatePickerViewDelegate,UIImagePickerControllerDelegate>
{
    NIAvatarObject *avatarObject;
}

@end

@implementation NIBasePhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    avatarObject = [NIAvatarObject getInstance];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(avatarHasChange) name:NotificationAvatarDidChange object:nil];
}

/**
 显示照片来源提示框
 */
- (void)showPhotoActionSheet
{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //创建取消按钮
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [action1 setValue:AlertBtnColor forKey:@"_titleTextColor"];
    
    //创建确定按钮
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    [action2 setValue:AlertBtnColor forKey:@"_titleTextColor"];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self localPhoto];
    }];
    [action3 setValue:AlertBtnColor forKey:@"_titleTextColor"];
    
    
    //添加文本框
    //添加按钮
    [alertC addAction:action1];
    [alertC addAction:action2];
    [alertC addAction:action3];
    //显示
    [self presentViewController:alertC animated:YES completion:nil];
}

// 开始拍照
-(void)takePhoto
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        //先检查相机可用是否
        BOOL cameraIsAvailable = [self checkCameraIsCheckPower:NO];
        if (YES == cameraIsAvailable) {
            [self presentViewController:picker animated:YES completion:nil];
        }
        
        else {
            NSString *mediaType = AVMediaTypeVideo;
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
            if(AVAuthorizationStatusNotDetermined == authStatus)
            {
                return ;
            }
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:@"请您在 “设置 - 隐私 - 相机” 中开启摄像头权限后重试" preferredStyle:UIAlertControllerStyleAlert];
            //创建取消按钮
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [action1 setValue:AlertBtnColor forKey:@"_titleTextColor"];
            
            [alertC addAction:action1];
            //显示
            [self presentViewController:alertC animated:YES completion:nil];

        }
        
    }
}
#pragma mark UIImagePickerControllerDelegate Call Back Implementation

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        NSString *key = nil;
        
        if (picker.allowsEditing)
        {
            key = UIImagePickerControllerEditedImage;
        }
        else
        {
            key = UIImagePickerControllerOriginalImage;
        }
        //获取图片
        UIImage *image = [info objectForKey:key];
        image = [self compressImage:image];
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:^{
            
        }];
        [avatarObject setTempAvatar:image];
        [self takePhotoFinish];
        [self avatarHasChange];
        
    }
}

-(UIImage *)compressImage:(UIImage *)myimage
{
    NSData *data=UIImageJPEGRepresentation(myimage, 1.0);
    
    if (data.length>10240*1024) {//10M以及以上
        data=UIImageJPEGRepresentation(myimage, 0.01);//压缩之后1M~
    }else if (data.length>5120*1024){//5M~10M
        data=UIImageJPEGRepresentation(myimage, 0.02);//压缩之后1M~2M
    }else if (data.length>2048*1024){//2M~5M
        data=UIImageJPEGRepresentation(myimage, 0.03);//压缩之后0.6M~1.5M
    }else{
        data=UIImageJPEGRepresentation(myimage, 0.05);//压缩之后0.5M~1M
    }
    return [UIImage imageWithData:data];
}

// 打开本地相册
-(void)localPhoto
{
    //本地相册不需要检查，因为UIImagePickerController会自动检查并提醒
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
    //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
    //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self.navigationController presentViewController:picker animated:YES completion:nil];
}

//检查相机是否可用
- (BOOL)checkCameraIsCheckPower:(BOOL)checkCameraPower
{
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(AVAuthorizationStatusRestricted == authStatus ||
       AVAuthorizationStatusDenied == authStatus)
    {
        //相机不可用
        return NO;
    }
    else if (AVAuthorizationStatusNotDetermined == authStatus)
    {
        NSString *mediaType = AVMediaTypeVideo;//读取媒体类型
        [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
            if (granted) {
                NSLog(@"允许了");
                if (checkCameraPower) {
                    [self checkCameraPower];
                }
                else
                {
                    
                    [self takePhoto];
                }
            }else
            {
                NSLog(@"拒绝了");
            }
        }];
        return NO;
    }
    else
    {
        //相机可用
        return YES;
    }
}

//压缩图片质量
-(UIImage *)reduceImage:(UIImage *)image percent:(float)percent
{
    NSData *imageData = UIImageJPEGRepresentation(image, percent);
    UIImage *newImage = [UIImage imageWithData:imageData];
    return newImage;
}
//压缩图片尺寸
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    //1.开启上下文
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
    //2.绘制图片
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    //3.从上下文中获取新图片
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    //4.关闭图形上下文
    UIGraphicsEndImageContext();
    //返回图片
    return newImage;
}


// 展示扫描界面
-(void)checkCameraPower
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        BOOL cameraIsAvailable = [self checkCameraIsCheckPower:YES];
        if (YES == cameraIsAvailable) {
            [self checkCameraPowerSuccess];
        }
        else {
            NSString *mediaType = AVMediaTypeVideo;
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
            if(AVAuthorizationStatusNotDetermined == authStatus)
            {
                return ;
            }
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:@"请您在 “设置 - 隐私 - 相机” 中开启摄像头权限后重试" preferredStyle:UIAlertControllerStyleAlert];
            //创建取消按钮
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [action1 setValue:AlertBtnColor forKey:@"_titleTextColor"];
            
            [alertC addAction:action1];
            //显示
            [self presentViewController:alertC animated:YES completion:nil];
            
        }
        
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 以下方法需要子类重写，以完成功能
-(void)avatarHasChange
{
}
-(void)takePhotoFinish
{
    
}

-(void)checkCameraPowerSuccess
{
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
